package com.twothreetwo.urlUtils
{
	import com.twothreetwo.jsonLoader.JSONLoader;
	import com.twothreetwo.objectLoader.ObjectLoader;
	import com.twothreetwo.xmlLoader.XMLLoader;
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.events.EventDispatcher;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	/**
	 * ...
	 * @author 232°Studios | Neil Glenister
	 * @link www.232studios.com
	 * @version = 0.1
	 */
	public class URLUtils extends EventDispatcher
	{
		
		/**
		 * Open an external URL. Returns a success/error string
		 * url: url to navigate to
		 * type: how the url opens
		 * @param	url
		 * @param	type
		 * @return success or error String
		 */
		public static function getURL(url:String, type:String = "_blank"):String
		{
			var request:URLRequest = new URLRequest(url);
			var success:String;
			
			try 
			{
				navigateToURL(request, type);
				success = "URL opened";
			} 
			catch (e:Error) 
			{
				success = "Error loading URL: " + e.message;
			}
			
			return success;
		}
		
		/**
		 * Returns a cache free url by adding a random number string to the end.
		 * @param	url
		 * @return
		 */
		public static function returnNoCacheUrl(url:String):String
		{
			var randUrl:String;
			
			if (url.indexOf("?") == -1)
			{
				randUrl = url + "?nocache=" + new Date().getTime();
			}
			else
			{
				randUrl = url + "&nocache=" + new Date().getTime();
			}
			
			return randUrl
		}
		
		/**
		 * Returns an object as a MovieClip.
		 * @param	url
		 * @return MovieClip
		 * @see URLUtilsEvent for Object loaded event.
		 */
		public static function returnObject(url:String):MovieClip
		{
			var objectLoader:ObjectLoader = new ObjectLoader();
			objectLoader.loadObject(url);
			
			return objectLoader;
		}
		
		/**
		 * Returns JSON as an Object.
		 * @param	url
		 * @return Object
		 * @see URLUtilsEvent for JSON loaded event.
		 */
		public static function returnJSON(url:String):JSONLoader
		{
			var jsonLoader:JSONLoader = new JSONLoader();
			jsonLoader.decodeJson(url);
			
			return jsonLoader;
		}
		
		/**
		 * Returns XML as XML.
		 * @param	url
		 * @return Object
		 * @see URLUtilsEvent for XML loaded event.
		 */
		public static function returnXML(url:String):XMLLoader
		{
			var xmlLoader:XMLLoader = new XMLLoader();
			xmlLoader.loadXML(url);
			
			return xmlLoader;
		}
	}

}